<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="tmsOrderId">
        <el-input
          v-model="queryParams.tmsOrderId"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerUserId">
        <el-input
          v-model="queryParams.customerUserId"
          placeholder="请输入客户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户公司编号" prop="customerCompanyId">
        <el-input
          v-model="queryParams.customerCompanyId"
          placeholder="请输入客户公司编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户公司" prop="customerCompanyName">
        <el-input
          v-model="queryParams.customerCompanyName"
          placeholder="请输入客户公司"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货人编号" prop="sendUserId">
        <el-input
          v-model="queryParams.sendUserId"
          placeholder="请输入发货人编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货人公司编号" prop="sendCompanyId">
        <el-input
          v-model="queryParams.sendCompanyId"
          placeholder="请输入发货人公司编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货人公司名称" prop="sendCompanyName">
        <el-input
          v-model="queryParams.sendCompanyName"
          placeholder="请输入发货人公司名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机姓名" prop="driverName">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承运车辆编号" prop="vanId">
        <el-input
          v-model="queryParams.vanId"
          placeholder="请输入承运车辆编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ems:emsOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ems:emsOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ems:emsOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ems:emsOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="emsOrderList"   @selection-change="handleSelectionChange"  >
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="订单id标识" align="center" prop="id" />-->
      <el-table-column label="订单编号" align="center" prop="tmsOrderId" />
      <el-table-column label="订单状态" align="center" prop="orderType" :formatter="orderTypeFormat" />
      <el-table-column label="总金额" align="center" prop="orderAllPrice" />
      <el-table-column label="传感器编号" align="center" prop="sensorIds" />
      <el-table-column label="gps编号" align="center" prop="gpsId" />
      <el-table-column label="冷藏箱编号" align="center" prop="refrigeratorId" />
      <el-table-column label="揽货时间" align="center" prop="transportTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customerUserId" />
      <el-table-column label="客户公司编号" align="center" prop="customerCompanyId" />
      <el-table-column label="客户公司" align="center" prop="customerCompanyName" />
      <el-table-column label="客户地址" align="center" prop="customerAddress" />
      <el-table-column label="收货确认时间" align="center" prop="customerGetTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.customerGetTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货人编号" align="center" prop="sendUserId" />
      <el-table-column label="发货人公司编号" align="center" prop="sendCompanyId" />
      <el-table-column label="发货人公司名称" align="center" prop="sendCompanyName" />
      <el-table-column label="发货人地址" align="center" prop="sendAddress" />
      <el-table-column label="司机电话" align="center" prop="driverPhone" />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="司机编号" align="center" prop="driverId" />
      <el-table-column label="承运车辆编号" align="center" prop="vanId" />
      <el-table-column label="承运车辆车牌号" align="center" prop="vanNumber" />
      <el-table-column label="承运车辆的司机姓名" align="center" prop="vanDriverName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-show = isAdmin
            v-hasPermi="['ems:emsOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="receiveOrder(scope.row,emsOrderList.indexOf(scope.row))"
            v-show = "role=='司机' && isReceive[emsOrderList.indexOf(scope.row)]==0 "
            v-hasPermi="['ems:emsOrder:edit']"
          >接单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-show = "role=='司机' && isReceive[emsOrderList.indexOf(scope.row)]==1 "
          >已接单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-show = isAdmin
            v-hasPermi="['ems:emsOrder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改同行单（业务）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="tmsOrderId">
          <el-input v-model="form.tmsOrderId" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择订单状态">
            <el-option
              v-for="dict in orderTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="orderAllPrice">
          <el-input v-model="form.orderAllPrice" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="gps编号" prop="gpsId">
          <el-input v-model="form.gpsId" placeholder="请输入gps编号" />
        </el-form-item>
        <el-form-item label="冷藏箱编号" prop="refrigeratorId">
          <el-input v-model="form.refrigeratorId" placeholder="请输入冷藏箱编号" />
        </el-form-item>
        <el-form-item label="揽货时间" prop="transportTime">
          <el-date-picker clearable size="small"
            v-model="form.transportTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择揽货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户" prop="customerUserId">
          <el-input v-model="form.customerUserId" placeholder="请输入客户" />
        </el-form-item>
        <el-form-item label="客户公司编号" prop="customerCompanyId">
          <el-input v-model="form.customerCompanyId" placeholder="请输入客户公司编号" />
        </el-form-item>
        <el-form-item label="客户公司" prop="customerCompanyName">
          <el-input v-model="form.customerCompanyName" placeholder="请输入客户公司" />
        </el-form-item>
        <el-form-item label="客户地址" prop="customerAddress">
          <el-input v-model="form.customerAddress" placeholder="请输入客户地址" />
        </el-form-item>
        <el-form-item label="收货确认时间" prop="customerGetTime">
          <el-date-picker clearable size="small"
            v-model="form.customerGetTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择收货确认时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货人编号" prop="sendUserId">
          <el-input v-model="form.sendUserId" placeholder="请输入发货人编号" />
        </el-form-item>
        <el-form-item label="发货人公司编号" prop="sendCompanyId">
          <el-input v-model="form.sendCompanyId" placeholder="请输入发货人公司编号" />
        </el-form-item>
        <el-form-item label="发货人公司名称" prop="sendCompanyName">
          <el-input v-model="form.sendCompanyName" placeholder="请输入发货人公司名称" />
        </el-form-item>
        <el-form-item label="发货人地址" prop="sendAddress">
          <el-input v-model="form.sendAddress" placeholder="请输入发货人地址" />
        </el-form-item>
        <el-form-item label="司机电话" prop="driverPhone">
          <el-input v-model="form.driverPhone" placeholder="请输入司机电话" />
        </el-form-item>
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
        </el-form-item>
        <el-form-item label="司机编号" prop="driverId">
          <el-input v-model="form.driverId" placeholder="请输入司机编号" />
        </el-form-item>
        <el-form-item label="承运车辆编号" prop="vanId">
          <el-input v-model="form.vanId" placeholder="请输入承运车辆编号" />
        </el-form-item>
        <el-form-item label="承运车辆车牌号" prop="vanNumber">
          <el-input v-model="form.vanNumber" placeholder="请输入承运车辆车牌号" />
        </el-form-item>
        <el-form-item label="承运车辆的司机姓名" prop="vanDriverName">
          <el-input v-model="form.vanDriverName" placeholder="请输入承运车辆的司机姓名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmsOrder, getEmsOrder, delEmsOrder, addEmsOrder, updateEmsOrder,getUser,getUserProfile,listVan  } from "@/api/ems/emsOrder";
import {  getVan, delVan, addVan, updateVan } from "@/api/ems/van";
// import {  getUserInfo } from "@/api/system/user";
export default {
  name: "EmsOrder",
  components: {
  },
  data() {
    return {
      //是否是管理员
      isAdmin: null,
      //是什么角色
      role: null,
      //司机是否接单
      isReceive: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 同行单（业务）表格数据
      emsOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 订单状态字典
      orderTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tmsOrderId: null,
        customerUserId: null,
        customerCompanyId: null,
        customerCompanyName: null,
        sendUserId: null,
        sendCompanyId: null,
        sendCompanyName: null,
        driverName: null,
        vanId: null,
      },
      // 查询车辆参数
      queryVanParams: {
        pageNum: 1,
        pageSize: 10,
        vanId: null,
        vanNumber: null,
        driverUserId: null,
        vanType: null
      },
      //修改车辆参数
      updateVanParams: {
        id: null,
        vanId: null,
        vanType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderAllPrice: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("order_type").then(response => {
      this.orderTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询同行单（业务）列表 */
    getList() {
      this.loading = true;
      listEmsOrder(this.queryParams).then(response => {
        console.log(response)
        this.emsOrderList = response[1].rows;
        this.total = response[1].total;
        this.loading = false;
        // 判断是否是管理员
        this.isAdmin = response[0];
        // 判断哪条订单已经被接单，哪些订单还没被接单
        console.log(response[1].rows)
        response[1].rows.forEach((item,index)=>{
          console.log(item)
          if(item.driverId!=null ){
            this.isReceive[index]=1;
          }else {
            this.isReceive[index]=0;
          }
        })
        // for(let i=0;i<=response[1].rows;i++){
        //   console.log(response[1].rows)
        //   //如果有司机姓名，说明已经被接单了
        //   if(response[1].rows[i].driverName!=null){
        //     this.isReceive[i]=1;
        //   }else{
        //     this.isReceive[i]=0;
        //   }
        // }
      });
      getUserProfile().then(res=>{
        this.role = res.roleGroup
      })
    },
    // 订单状态字典翻译
    orderTypeFormat(row, column) {
      return this.selectDictLabel(this.orderTypeOptions, row.orderType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tmsOrderId: null,
        orderType: null,
        orderAllPrice: null,
        sensorIds: null,
        gpsId: null,
        refrigeratorId: null,
        transportTime: null,
        customerUserId: null,
        customerCompanyId: null,
        customerCompanyName: null,
        customerAddress: null,
        customerGetTime: null,
        sendUserId: null,
        sendCompanyId: null,
        sendCompanyName: null,
        sendAddress: null,
        driverPhone: null,
        driverName: null,
        driverId: null,
        vanId: null,
        vanNumber: null,
        vanDriverName: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加同行单（业务）";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmsOrder(id).then(response => {
        // 返回成功赋值给表单
        this.form = response.data;
        // 是否显示弹出层
        this.open = true;
        // 修改标题
        this.title = "修改同行单（业务）";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEmsOrder(this.form).then(response => {
              console.log(response[0])
              this.isAdmin = response[0];
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(err=>{
              console.log(err)
            });
          } else {
            addEmsOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 司机接单*/
    receiveOrder(row,index){
      //已接单
      this.isReceive[index] = 1;
      this.reset();
      const id = row.id || this.ids
      getEmsOrder(id).then(response => {
        console.log(response)
        // 返回成功赋值给表单
        this.form = response.data;
        // 是否显示弹出层
        this.open = false;
        // 修改标题
        this.title = "修改同行单（业务）";
        //获取当前用户个人信息
        getUserProfile().then(res=>{
          console.log(res)
          this.form.driverPhone = res.data.phonenumber;
          this.form.driverName = res.data.nickName;
          this.form.driverId = res.data.userId;
          this.form.vanDriverName = res.data.nickName;
          this.queryVanParams.driverUserId = res.data.userId;
          //查询车辆
          listVan(this.queryVanParams).then(resp=>{
            console.log(resp)
            this.form.vanId = resp.rows[0].vanId;
            this.form.vanNumber =  resp.rows[0].vanNumber;
            //设置修改车辆状态的参数：vanId
            this.updateVanParams.vanId = resp.rows[0].vanId;
            this.updateVanParams.id = resp.rows[0].id;
            const that = this;
            setTimeout(function () {
              if (that.form.id != null){
                console.log(that.form)
                updateEmsOrder(that.form).then(response => {
                  console.log(response[1])
                  that.msgSuccess("接单成功");
                  that.open = false;
                  that.getList();
                  //订单被司机接单，更新完订单状态之后把车辆状态更新,vantype=0:在途
                  that.updateVanParams.vanType = 0;
                  updateVan(that.updateVanParams).then(response2=>{
                    console.log(response2)
                  })
                }).catch(err=>{
                  console.log(err)
                });
              }
            },10)
          })
        })
        // if (this.form.id != null){
        //   console.log(this.form)
        //   updateEmsOrder(this.form).then(response => {
        //     console.log(response[1])
        //     this.msgSuccess("接单成功");
        //     this.open = true;
        //     this.getList();
        //   }).catch(err=>{
        //     console.log(err)
        //   });
        // }
          // updateEmsOrder(this.form).then(response=>{
        //   //获取当前用户姓名 user4
        //   const name = response[2]
        //   console.log(response)
        //   //获取当前用户信息
        //   getUserProfile().then(res=>{
        //     console.log(res)
        //     this.driverPhone = res.data.phonenumber;
        //   })
        //
        // })
        // const that = this;
        // setTimeout(function () {
        //   if (that.form.id != null){
        //     console.log(that.form)
        //     updateEmsOrder(that.form).then(response => {
        //       console.log(response[1])
        //       that.msgSuccess("接单成功");
        //       that.open = false;
        //       that.getList();
        //       //订单被司机接单，更新完订单状态之后把车辆状态更新,vantype=0:在途
        //       that.updateVanParams.vanType = 0;
        //       updateVan(that.updateVanParams).then(response2=>{
        //         console.log(response2)
        //       })
        //     }).catch(err=>{
        //       console.log(err)
        //     });
        //   }
        // },500)
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除同行单（业务）编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEmsOrder(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/emsOrder/export', {
        ...this.queryParams
      }, `ems_emsOrder.xlsx`)
    }
  }
};
</script>
